import React, { useState, useEffect } from 'react';
import { DiaryTemplate, TemplateSection } from '../types/templates';
import { ChevronDown, ChevronUp, HelpCircle, Type, AlignLeft } from 'lucide-react';

interface TemplateEditorProps {
  template: DiaryTemplate;
  initialSections?: { [sectionId: string]: string };
  onChange: (sections: { [sectionId: string]: string }) => void;
  onContentChange?: (content: string) => void;
}

const TemplateEditor: React.FC<TemplateEditorProps> = ({
  template,
  initialSections = {},
  onChange,
  onContentChange
}) => {
  const [sectionValues, setSectionValues] = useState<{ [sectionId: string]: string }>(initialSections);
  const [expandedSections, setExpandedSections] = useState<{ [sectionId: string]: boolean }>({});
  const [showPrompts, setShowPrompts] = useState<{ [sectionId: string]: boolean }>({});
  
  // Sort sections by order
  const sortedSections = [...template.sections].sort((a, b) => a.order - b.order);
  
  useEffect(() => {
    // Initialize expanded state for required sections
    const initialExpanded: { [sectionId: string]: boolean } = {};
    sortedSections.forEach((section) => {
      if (section.required) {
        initialExpanded[section.id] = true;
      }
    });
    setExpandedSections(initialExpanded);
  }, [template]);
  
  useEffect(() => {
    onChange(sectionValues);
    
    // Generate combined content for backward compatibility
    if (onContentChange) {
      const combinedContent = sortedSections
        .filter(section => sectionValues[section.id]?.trim())
        .map(section => {
          const content = sectionValues[section.id];
          return `**${section.title}**\n\n${content}`;
        })
        .join('\n\n---\n\n');
      
      onContentChange(combinedContent);
    }
  }, [sectionValues, onChange, onContentChange, sortedSections]);
  
  const handleSectionChange = (sectionId: string, value: string) => {
    setSectionValues(prev => ({
      ...prev,
      [sectionId]: value
    }));
  };
  
  const toggleSection = (sectionId: string) => {
    setExpandedSections(prev => ({
      ...prev,
      [sectionId]: !prev[sectionId]
    }));
  };
  
  const togglePrompt = (sectionId: string) => {
    setShowPrompts(prev => ({
      ...prev,
      [sectionId]: !prev[sectionId]
    }));
  };
  
  const getSectionWordCount = (content: string) => {
    return content.trim().split(/\s+/).filter(word => word.length > 0).length;
  };
  
  const renderSection = (section: TemplateSection) => {
    const isExpanded = expandedSections[section.id];
    const showPrompt = showPrompts[section.id];
    const content = sectionValues[section.id] || '';
    const wordCount = getSectionWordCount(content);
    const isEmpty = !content.trim();
    
    return (
      <div key={section.id} className="border border-gray-200 rounded-lg overflow-hidden">
        {/* Section Header */}
        <div 
          className={`p-4 cursor-pointer transition-colors ${
            isExpanded ? 'bg-blue-50 border-b border-gray-200' : 'bg-gray-50 hover:bg-gray-100'
          }`}
          onClick={() => toggleSection(section.id)}
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <div className="flex items-center space-x-2">
                <h3 className={`font-medium ${
                  section.required ? 'text-gray-900' : 'text-gray-700'
                }`}>
                  {section.title}
                  {section.required && <span className="text-red-500 ml-1">*</span>}
                </h3>
                
                {section.prompt && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      togglePrompt(section.id);
                    }}
                    className="p-1 text-gray-400 hover:text-blue-500 transition-colors"
                    title="Show/hide writing prompt"
                  >
                    <HelpCircle className="w-4 h-4" />
                  </button>
                )}
              </div>
              
              {!isEmpty && (
                <div className="flex items-center space-x-2 text-sm text-gray-500">
                  <Type className="w-3 h-3" />
                  <span>{wordCount} words</span>
                </div>
              )}
            </div>
            
            <div className="flex items-center space-x-2">
              {!isEmpty && (
                <div className={`w-2 h-2 rounded-full ${
                  section.required ? 'bg-green-500' : 'bg-blue-500'
                }`} />
              )}
              
              {isExpanded ? (
                <ChevronUp className="w-4 h-4 text-gray-500" />
              ) : (
                <ChevronDown className="w-4 h-4 text-gray-500" />
              )}
            </div>
          </div>
          
          {/* Prompt */}
          {showPrompt && section.prompt && (
            <div className="mt-2 p-3 bg-blue-100 rounded-lg">
              <div className="flex items-start space-x-2">
                <AlignLeft className="w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0" />
                <p className="text-sm text-blue-800">{section.prompt}</p>
              </div>
            </div>
          )}
        </div>
        
        {/* Section Content */}
        {isExpanded && (
          <div className="p-4">
            <textarea
              value={content}
              onChange={(e) => handleSectionChange(section.id, e.target.value)}
              placeholder={section.placeholder || `Write about ${section.title.toLowerCase()}...`}
              className={`w-full min-h-[120px] p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-y ${
                section.required && isEmpty ? 'border-red-300 focus:ring-red-500' : ''
              }`}
              rows={4}
            />
            
            {section.required && isEmpty && (
              <p className="mt-2 text-sm text-red-600">
                This section is required for the {template.name} template.
              </p>
            )}
            
            <div className="mt-2 flex items-center justify-between text-xs text-gray-500">
              <span>
                {content.length > 0 ? `${content.length} characters` : 'Start writing...'}
              </span>
              
              {section.prompt && !showPrompt && (
                <button
                  onClick={() => togglePrompt(section.id)}
                  className="text-blue-600 hover:text-blue-700 transition-colors"
                >
                  Show writing prompt
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    );
  };
  
  const getCompletionStatus = () => {
    const requiredSections = sortedSections.filter(s => s.required);
    const completedRequired = requiredSections.filter(s => sectionValues[s.id]?.trim()).length;
    const totalSections = sortedSections.length;
    const completedTotal = sortedSections.filter(s => sectionValues[s.id]?.trim()).length;
    
    return {
      requiredCompleted: completedRequired,
      requiredTotal: requiredSections.length,
      totalCompleted: completedTotal,
      totalSections,
      isComplete: completedRequired === requiredSections.length
    };
  };
  
  const status = getCompletionStatus();
  
  return (
    <div className="space-y-4">
      {/* Template Header */}
      <div className="bg-gradient-to-r from-blue-50 to-indigo-50 p-4 rounded-lg border border-blue-200">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-semibold text-gray-900 mb-1">
              {template.name} Template
            </h2>
            <p className="text-sm text-gray-600">{template.description}</p>
          </div>
          
          <div className="text-right">
            <div className="text-sm font-medium text-gray-900">
              {status.totalCompleted}/{status.totalSections} sections
            </div>
            <div className="text-xs text-gray-500">
              {status.requiredCompleted}/{status.requiredTotal} required
            </div>
            
            {status.isComplete && (
              <div className="mt-1 inline-flex items-center px-2 py-1 rounded-full text-xs bg-green-100 text-green-800">
                ✓ Complete
              </div>
            )}
          </div>
        </div>
        
        {/* Progress Bar */}
        <div className="mt-3">
          <div className="flex justify-between text-xs text-gray-600 mb-1">
            <span>Progress</span>
            <span>{Math.round((status.totalCompleted / status.totalSections) * 100)}%</span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-2">
            <div 
              className="bg-blue-500 h-2 rounded-full transition-all duration-300"
              style={{ width: `${(status.totalCompleted / status.totalSections) * 100}%` }}
            />
          </div>
        </div>
      </div>
      
      {/* Template Sections */}
      <div className="space-y-3">
        {sortedSections.map(renderSection)}
      </div>
      
      {/* Quick Actions */}
      <div className="flex flex-wrap gap-2 pt-4 border-t border-gray-200">
        <button
          onClick={() => {
            const newExpanded: { [sectionId: string]: boolean } = {};
            sortedSections.forEach(section => {
              newExpanded[section.id] = true;
            });
            setExpandedSections(newExpanded);
          }}
          className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
        >
          Expand All
        </button>
        
        <button
          onClick={() => {
            const newExpanded: { [sectionId: string]: boolean } = {};
            sortedSections.forEach(section => {
              if (section.required) {
                newExpanded[section.id] = true;
              }
            });
            setExpandedSections(newExpanded);
          }}
          className="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
        >
          Collapse All
        </button>
        
        <button
          onClick={() => {
            const newPrompts: { [sectionId: string]: boolean } = {};
            sortedSections.forEach(section => {
              if (section.prompt) {
                newPrompts[section.id] = true;
              }
            });
            setShowPrompts(newPrompts);
          }}
          className="px-3 py-1 text-sm bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition-colors"
        >
          Show All Prompts
        </button>
      </div>
    </div>
  );
};

export default TemplateEditor;